package m202406.d05;

import java.util.*;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/5 22:03
 */
public class OD_T03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] in = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int[] pre = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        Node tree = build(in, 0, in.length, pre, 0, pre.length);
        travel(tree);
    }

    private static void travel(Node node) {
        if (node == null) {
            return;
        }
        travel(node.left);
        System.out.print(node.sum + " ");
        travel(node.right);
    }

    private static Node build(int[] in, int is, int ie, int[] pre, int ps, int pe) {
        if (ie - is == 0) {
            return null;
        }
        Node node = new Node(pre[ps]);
        List<Integer> indexes = findIndex(pre[ps], in, is, ie);
        int index = indexes.get(0);
        for (Integer i : indexes) {
            if (test(in, is, i, pre, ps + 1, ps + (i - is)+1) && test(in, i + 1, ie, pre, ps + (i - is) + 1, pe)) {
                index = i;
                break;
            }
        }
        node.left = build(in, is, index, pre, ps + 1, ps + (index - is)+1);
        node.right = build(in, index + 1, ie, pre, ps + (index - is) + 1, pe);
        int sum = 0;
        if (node.left != null) {
            sum = node.left.val + sum + node.left.sum;
        }
        if (node.right != null) {
            sum = node.right.val + sum + node.right.sum;
        }
        node.sum = sum;
        return node;
    }

    private static List<Integer> findIndex(int target, int[] in, int is, int ie) {
        List<Integer> indexes = new ArrayList<>();
        for (int i = is; i < ie; i++) {
            if (in[i] == target) {
                indexes.add(i);
            }
        }
        return indexes;
    }

    private static boolean test(int[] in, int is, int ie, int[] pre, int ps, int pe) {
        Set<Integer> iSet = new HashSet<>();
        Set<Integer> pSet = new HashSet<>();
        for (int i = is; i < ie; i++) {
            iSet.add(in[i]);
        }
        for (int i = ps; i < pe; i++) {
            pSet.add(pre[i]);
        }
        return iSet.containsAll(pSet) && pSet.containsAll(iSet);
    }


    private static class Node {
        private int val;
        private int sum;
        private Node left;
        private Node right;

        public Node(int val) {
            this.val = val;
        }
    }
}
